/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radio_GUI;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.swing.table.DefaultTableModel;
import model.Song;
import model.Album;
import model.Artist;
import model.Musicgroup;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Playlist;



// imports gia XML write and read
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author ace5
 */
public class PlaylistEdit extends javax.swing.JFrame {

    //A.T. MODELS OF LISTS
    DefaultTableModel modelALL = new DefaultTableModel();
    DefaultTableModel modelPL = new DefaultTableModel();
    private final EntityManager em; //A.T. o entity manger tis basis
    private List<Song> songList; //A.T. xrisimopoiite stin apothikeysh
    PlaylistForm parentForm;  //A.T. i playlistForm form.
    private boolean delForm = false;//A.T. H forma einai gia diagrafi playlist
    private boolean eniForm = false;//A.T. H forma einai gia enimerosh playlist
    private Playlist plEDORDEL;//A.T. antikimeno playlist pros diagrafi enimer.
    private long pLIdIn ;//A.T. playlistId gia epeksergasia h diagrafi
    /**
     * Creates new form PlaylistEdit
     */
    public PlaylistEdit(PlaylistForm plform) {
      
    
        
        this.pLIdIn = Long.MAX_VALUE;
        this.songList = new ArrayList<Song>();
        this.parentForm = plform;
        this.em=DBManager.getEm();
        
        initComponents();
        
        //A.T. simplirose to pedio is Hmerominias me tin torini ora kai mera
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateCreated = sdf.format(Calendar.getInstance().getTime());
        jTextFieldCreat.setText(dateCreated);
        
        modelPL = (DefaultTableModel) jTablePL.getModel();
        modelALL = (DefaultTableModel) jTableAll.getModel();
        //A.T. "gemise" to jtable(deksi) me ola ta diathesima tragoudia tis DB
        this.setAllList();
        //A.T. "gemise" to jtable(aristero) me ta tragoudia tou Playlist
        this.setPLList();
    }
    /*
    *A.T. Constractor gia delete playlist
    */
    public PlaylistEdit(PlaylistForm plform,Playlist pl,boolean del) {
      
      
        
        this.songList = pl.getSongList();
        this.plEDORDEL = pl;
        this.parentForm = plform;
        
        initComponents();
        
        this.delForm = del;
        this.pLIdIn = pl.getPlaylistId();
        modelPL = (DefaultTableModel) jTablePL.getModel();
        modelALL = (DefaultTableModel) jTableAll.getModel();
        
        if (this.delForm){//A.T. h forma einai gia diagrafi tou antikimenou
            jButtonSave.setText("Διαγραφή");
            jTextFieldName.setEnabled(false);
            jTextFieldDescr.setEnabled(false);
            jTextFieldCreat.setEnabled(false);
            jTextFieldName.setText(pl.getName());
            jTextFieldDescr.setText(pl.getPerigrafi());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateCreated = sdf.format(pl.getCreationdate().getTime());
            jTextFieldCreat.setText(dateCreated);
            jTableAll.setEnabled(false);
            jTablePL.setEnabled(false);
            jButtonIn.setEnabled(false);
            jButtonOut.setEnabled(false);
            jButtonRXML.setEnabled(false);
            
        } else if(!this.delForm) {//A.T. h forma einai gia metaboli
            
            this.eniForm = true; //A.T. metaboli form xrisimopoiite sto 
                                 //Apothikeusi button
            //A.T. Simplirose ta pedia me to antikimeno Playlist tis parametrou
            jTextFieldName.setText(pl.getName());
            jTextFieldDescr.setText(pl.getPerigrafi());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateCreated = sdf.format(pl.getCreationdate().getTime());
            jTextFieldCreat.setText(dateCreated);
            
        }
        //A.T. O entity manager
        this.em=DBManager.getEm();
        //A.T. "gemise" to jtable(deksi) me ola ta diathesima tragoudia tis DB
        this.setAllList();
        //A.T. "gemise" to jtable(aristero) me ta tragoudia tou Playlist
        this.setPLList();
    }

    
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        file1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldName = new javax.swing.JTextField();
        jTextFieldDescr = new javax.swing.JTextField();
        jTextFieldCreat = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jButtonIn = new javax.swing.JButton();
        jButtonOut = new javax.swing.JButton();
        jTextFieldSearch = new javax.swing.JTextField();
        jButtonSearch = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableAll = new javax.swing.JTable();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTablePL = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jButtonWXML = new javax.swing.JButton();
        jButtonRXML = new javax.swing.JButton();
        jButtonSave = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();

        file1.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
        file1.setDialogTitle("File to Save Dialog");
        file1.setFileFilter(new MyCustomFilter());

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel2.setText("Όνομα:");

        jLabel3.setText("Περιγραφή:");

        jLabel4.setText("Ημ/νια Δημιου.:");

        jTextFieldName.setText("Όνομα....");

        jTextFieldDescr.setText("Περιγραφή.......");

        jTextFieldCreat.setText("Δημιουργιθηκε..");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldDescr, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldCreat, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldDescr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldCreat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(50, Short.MAX_VALUE))
        );

        jLabel1.setText("Φόρμα Διαχείρισης Λίστας");

        jLabel5.setText("Τραγούδια Διαθέσιμα");

        jLabel6.setText("Τραγούδια Λίστας");

        jButtonIn.setText("<--Εισαγωγή");
        jButtonIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInActionPerformed(evt);
            }
        });

        jButtonOut.setText("Διαγραφή -->");
        jButtonOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOutActionPerformed(evt);
            }
        });

        jTextFieldSearch.setText("*");
        jTextFieldSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldSearchActionPerformed(evt);
            }
        });

        jButtonSearch.setText("Αναζήτηση");
        jButtonSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSearchActionPerformed(evt);
            }
        });

        jTableAll.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Τίτλος", "Δημιουργός", "Διάρκεια"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(jTableAll);

        jTablePL.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Τίτλος", "Δημιουργός", "Διάρκεια"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane4.setViewportView(jTablePL);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonIn)
                    .addComponent(jButtonOut))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonSearch)
                    .addComponent(jTextFieldSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel5)
                .addGap(232, 232, 232))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jTextFieldSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonSearch)
                        .addContainerGap(210, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonIn)
                        .addGap(32, 32, 32)
                        .addComponent(jButtonOut)
                        .addGap(99, 99, 99))))
        );

        jTablePL.setModel(new javax.swing.table.DefaultTableModel(null,
            new String [] {
                "Τίτλος","Δημιουργος","Διαρκεια"
            }));

            jButtonWXML.setText("Εξαγωγή Λίστας Σε XML");
            jButtonWXML.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButtonWXMLActionPerformed(evt);
                }
            });

            jButtonRXML.setText("Εισαγωγή Λίστας από Αρχείο XML");
            jButtonRXML.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButtonRXMLActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
            jPanel3.setLayout(jPanel3Layout);
            jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addGap(25, 25, 25)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jButtonRXML, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonWXML, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap(75, Short.MAX_VALUE))
            );
            jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jButtonWXML)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jButtonRXML)
                    .addContainerGap(20, Short.MAX_VALUE))
            );

            jButtonSave.setText("Αποθήκευση");
            jButtonSave.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButtonSaveActionPerformed(evt);
                }
            });

            jButtonCancel.setText("Ακύρωση");
            jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButtonCancelActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(188, 188, 188)
                            .addComponent(jLabel1)
                            .addGap(0, 0, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(12, 12, 12)
                                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 160, Short.MAX_VALUE)
                                    .addComponent(jButtonSave)
                                    .addGap(31, 31, 31)
                                    .addComponent(jButtonCancel)
                                    .addGap(99, 99, 99))
                                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addComponent(jLabel1)
                    .addGap(18, 18, 18)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButtonSave)
                                .addComponent(jButtonCancel))
                            .addGap(43, 43, 43))
                        .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

    private void jButtonInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInActionPerformed
        // TODO add your handling code here:
        //A.T. GET Models of  tables
        modelALL = (DefaultTableModel) jTableAll.getModel();
        modelPL = (DefaultTableModel) jTablePL.getModel();
        //A.T. index epilogis ston pinaka jTableALL
        int row = jTableAll.convertRowIndexToModel(jTableAll.getSelectedRow());
        
        //System.out.println(row +" val:"+modelALL.getRowCount());
        //A.T. Pernoyme to tragoudi tis siras row
        if (row >= 0 && row < modelALL.getRowCount()){
            Object[] data =  {modelALL.getValueAt(row,0),
                    modelALL.getValueAt(row,1),modelALL.getValueAt(row,2)};
            //System.out.println(data);
            //A.T. Prosthetoume to tragoudi sto Playlist ...me elegxo diplotipou
            
            boolean diplotipo = false;//A.T. bool metabliti an iparxi idi to 
                                      //tragoudi stin playlist
            //A.T. Diapername to aristero jTable kai elegxoume ta 3 pedia tou
            // an einai idia me to data poy theloume na isagoume
            for (int rowNo = 0; rowNo < modelPL.getRowCount();rowNo++){
                if(modelPL.getValueAt(rowNo, 0).equals(data[0])){
                    if(modelPL.getValueAt(rowNo, 1).equals(data[1])){
                        if(modelPL.getValueAt(rowNo, 2).equals(data[2])){
                            diplotipo = true;//A.T. Kai ta 3 pedia einai idia
                        }
                    }
                }   
            }
            if(!diplotipo){//A.T. Den einai diplotipo opote to prosthetoume
                modelPL.addRow(data);
            }else{//A.T. Diplpotipo ara minima lathous
                JOptionPane.showMessageDialog(this,
                        "Το τραγούδι υπαρχει ηδη στη Playlist...");//P.A
            }
        }else { //P.A
            JOptionPane.showMessageDialog(this,
                        "Πρέπει να επιλέξετε μια γραμμή απο τον πινακα..");//P.A
        }
        //modelPL.fireTableRowsInserted //A.T. den xriazete telika
          //  (modelPL.getRowCount(),modelPL.getRowCount());
    }//GEN-LAST:event_jButtonInActionPerformed

    private void jButtonOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOutActionPerformed
        //A.T. pernoume ta Model ton pinakvn
        modelALL = (DefaultTableModel) jTableAll.getModel();
        modelPL = (DefaultTableModel) jTablePL.getModel();
        //A.T. index epilogis ston pinaka jTableALL
        int row = jTablePL.convertRowIndexToModel(jTablePL.getSelectedRow());
        
        //System.out.println(row +" val:"+modelALL.getRowCount());
        //A.T. Pernoyme to tragoudi tis siras row
        if (row >= 0 && row < modelPL.getRowCount()){
            //A.T. Aferoume thn grammh apo to model
            modelPL.removeRow(row);
            System.out.println(" row to get out: " + row +" rowcountmodel" +
                    modelPL.getRowCount()+" Slis:" + songList.size());
            if (modelPL.getRowCount() == 0){
                modelPL.setRowCount(0);
                songList.clear();
                System.out.println(" row to get out: " + row +" rowcountmodel" +
                    modelPL.getRowCount()+" Slis:" + songList.size());
            }
            
        }else { //P.A
            JOptionPane.showMessageDialog(this,
                        "Πρέπει να επιλέξετε μια γραμμή απο τον πινακα");//P.A
        }
    }//GEN-LAST:event_jButtonOutActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        // TODO add your handling code here:
        this.dispose();//A.T. klisimo playlistedit form
        this.parentForm.setVisible(true);  //A.T. emfanish playlistForm
    }//GEN-LAST:event_jButtonCancelActionPerformed
    
    /*
    *A.T. Apothikeysh tvn alagon stin playlistEdit Form kai
    *epistrofi stin playlistForm
    */
    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        // TODO add your handling code here:
        
        int plTime=0;//A.T. metabliti me tin diarkia se deyterolepta
        
        if (!delForm || eniForm){//A.T. An einai dimiourgia neou, h modify Form
            
            Playlist playlist;//A.T. to antikeimeno pou tha dimioyrgisoume 
                              //h tha metabaloume
            songList.clear();//A.T. "Katharizoume" tin metabliti songlist
                                 // gia na min ta paroume 2 fores ta stoixia tis
                                 //,tin gemizoume me query parakato me query
            //A.T. antikimeno playlist poy tha eisagoume sthn BD
            if (eniForm){//A.T. Theloume metaboli tou antikimenou pou
                         //perastike san parametros
                playlist = this.plEDORDEL;
                
                
            }else {//A.T. Theloume dimiourgia neou antikimenou Playlist
                playlist= new Playlist();
            }
                    
            //A.T. set ta ipolipa pedia tou playlist apo ta pedia tis formas
            playlist.setName(jTextFieldName.getText());
            playlist.setPerigrafi(jTextFieldDescr.getText());
            playlist.setCreationdate(Calendar.getInstance().getTime());
        
            //A.T. Songlist apo ModelPL
            modelPL = (DefaultTableModel) jTablePL.getModel();
            int noOfSongs= modelPL.getRowCount();
            for (int i = 0 ; i < noOfSongs ; i++){
                String songTi = modelPL.getValueAt( i,  0 ).toString();
                //System.out.println(playlist.toString()+" > "+songTi);
                TypedQuery<Song> qsongId = em.createQuery("SELECT s "
                    + "FROM Song s WHERE s.title = :songTiP ", Song.class);
                songList.add(qsongId.setParameter("songTiP"
                    , songTi).getSingleResult());
                
            }
            playlist.setSongList(songList);
            //System.out.println(playlist.toString());
            
            for(Song s : songList){
                plTime += s.getDuration();//A.T. prosthese diarkia
            }
            if(plTime >= 1800){//A.T. diarkeia 30 lepton 
                //A.T. xrhsh exception
                try{
                    if (eniForm){
                        em.getTransaction().begin();           
                        em.merge(playlist);
                        em.getTransaction().commit();
                    }else {
                        //A.T. apothikeysh me entity manager
                        em.getTransaction().begin();           
                        em.persist(playlist);
                        em.getTransaction().commit();
                    }
                }catch(Exception e){
                    System.out.println(e);
                }
            }else{
                JOptionPane.showMessageDialog(this,
                        "Η λιστα πρεπει να ειναι τουλαχιστον 30 λεπτα σε "
                                + "διαρκεια και οχι :" + plTime/60);
                
            }
                         
        }else if (delForm){
            //A.T. xrhsh exception
            try{
                //A.T. diagrafi antikimenou me em stin DB
                em.getTransaction().begin();
                Playlist toBeRemoved = em.merge(this.plEDORDEL);
                em.remove(toBeRemoved);//A.T. Diagrafi playlist
                em.getTransaction().commit();
            }catch(Exception e){
                System.out.println(e);
            }
        }
        
        if(delForm || (plTime >= 1800)){//A.T. sinexia mono an einai diagrafi 
                                        //h diarkia > 10lepton
            this.dispose();//A.T. kripsimo formas
            this.parentForm.setVisible(true);  //A.T. emfanish playlistForm
        }
        
    }//GEN-LAST:event_jButtonSaveActionPerformed

    private void jButtonWXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonWXMLActionPerformed
        //A.T. Basi tou simple Jpa XML arxiou 
        try{
            DocumentBuilderFactory docFactory =
                    DocumentBuilderFactory.newInstance();//A.T. parser DOM creat
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            
            Element rootElement = doc.createElement("Playlist");//A.T.
        // dimiourgia root element aki stin sinexia prosthiki tag sto root elem
            doc.appendChild(rootElement);
            
            Element pl_title = doc.createElement("Playlist_title"); 
            pl_title.appendChild(doc.createTextNode(jTextFieldName.getText())); 
            rootElement.appendChild(pl_title);
           
            Element pl_perig = doc.createElement("Playlist_perig");
            pl_perig.appendChild(doc.createTextNode(jTextFieldDescr.getText())); 
            rootElement.appendChild(pl_perig);
            
            
            Element pl_date = doc.createElement("Playlist_date"); 
            pl_date.appendChild(doc.createTextNode(jTextFieldCreat.getText())); 
            rootElement.appendChild(pl_date);
            
            Element songList = doc.createElement("SongList"); // δημιουργώ ένα
            rootElement.appendChild(songList);
            
            List<Song> songListXML = new ArrayList();
            modelPL = (DefaultTableModel) jTablePL.getModel();
            int noOfSongs= modelPL.getRowCount();
            for (int i = 0 ; i < noOfSongs ; i++){
                String songTi = modelPL.getValueAt( i,  0 ).toString();
                //System.out.println(playlist.toString()+" > "+songTi);
                TypedQuery<Song> qsongId = em.createQuery("SELECT s "
                    + "FROM Song s WHERE s.title = :songTiP ", Song.class);
                songListXML.add(qsongId.setParameter("songTiP"
                    , songTi).getSingleResult());
            }
        
            for (Song source: songListXML){
            
                Element songEle = doc.createElement("Song"); // δημιουργώ ένα
                songList.appendChild(songEle);
                
                Element title = doc.createElement("Title");
                title.appendChild(doc.createTextNode(source.getTitle())); 
                songEle.appendChild(title);
                
                String artists= "";
                Album al = source.getAlbumId();
                String artistAll = "";
                for (model.AlbumArtist  aa : al.getAlbumArtistList()){
                    Artist a =aa.getArtistId();
                    if (artists.equals("")){
                        artistAll = a.getArtisticname();   
                    }else{
                        artistAll = artists + " , " + a.getArtisticname();
                    }
                    artists = artistAll;
                }
                for (model.AlbumMg  aa : al.getAlbumMgList()){
                    Musicgroup a =aa.getMusicgroupId();
                    if (artists.equals("")){
                        artistAll = a.getName();   
                    }else{
                        artistAll = artists + " , " + a.getName();
                    }
                    artists = artistAll;
                }
                Element artName = doc.createElement("Artist");
                artName.appendChild(doc.createTextNode(artists)); 
                songEle.appendChild(artName);
                
                //Attr durat = doc.createAttribute("Duration");
                //durat.setValue(Integer.toString(source.getDuration()));
                //songEle.setAttributeNode(durat);
         
                Element durat = doc.createElement("Duration");
                durat.appendChild(doc.createTextNode
                        (String.valueOf(source.getDuration())));
                songEle.appendChild(durat);
            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result;
 
            file1.setDialogTitle("Select file to save...");
            int returnVal = file1.showSaveDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                 File file = file1.getSelectedFile();
                try {
                  // What to do with the file, e.g. display it in a TextArea
                  //  textarea.read( new FileReader( file.getAbsolutePath() ), null );
                    result = new StreamResult(file.getAbsolutePath());
                    transformer.transform(source, result);
                    System.out.println("File saved!");
                } catch (Exception ex) {
                    System.out.println("problem accessing "
                                         + "file"+file.getAbsolutePath());
                }
            } else {
                System.out.println("File access cancelled by user.");
            }


        }catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        }catch (TransformerException tfe) {
            tfe.printStackTrace();
        }

    }//GEN-LAST:event_jButtonWXMLActionPerformed

    private void jButtonRXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRXMLActionPerformed
        // TODO add your handling code here:
        try{
               
            DocumentBuilderFactory docFactory =
                    DocumentBuilderFactory.newInstance();//A.T. 
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            file1.setDialogTitle("Select file to open...");
            int returnVal = file1.showOpenDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = file1.getSelectedFile();
                try {

                    doc = docBuilder.parse(file);
                    System.out.println("File" + file.getAbsolutePath() 
                                                    + "selected to Open!");
                } catch (Exception ex) {
                    System.out.println("problem accessing "
                                + "file"+file.getAbsolutePath());
                }
            } else {
                System.out.println("File access cancelled by user.");
            }
            //System.out.println("PLTitle= " +
            //    doc.getElementsByTagName("Playlist_title").item
            //            (0).getTextContent());
            jTextFieldName.setText(doc.getElementsByTagName
                            ("Playlist_title").item(0).getTextContent());   
            jTextFieldDescr.setText(doc.getElementsByTagName
                            ("Playlist_perig").item(0).getTextContent());
            jTextFieldCreat.setText(doc.getElementsByTagName
                            ("Playlist_date").item(0).getTextContent());
            //A.T. to aristero jtable (ta tragoudia)
            modelPL = (DefaultTableModel) jTablePL.getModel();
            for (int i=0 ; i < doc.getElementsByTagName("Title").getLength()
                                                                        ;i++){
                Object[] rowToAdd = {doc.getElementsByTagName
                                            ("Title").item(i).getTextContent(),
                           doc.getElementsByTagName
                                            ("Artist").item(i).getTextContent(),
                           doc.getElementsByTagName
                                        ("Duration").item(i).getTextContent()};
                modelPL.addRow(rowToAdd);
            }
        }catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        }
    }//GEN-LAST:event_jButtonRXMLActionPerformed

    private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSearchActionPerformed
        // TODO add your handling code here:
        setAllList();//A.T. enimerosi listas diathsimon tragoudion(deksi jTable)
    }//GEN-LAST:event_jButtonSearchActionPerformed

    private void jTextFieldSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldSearchActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldSearchActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PlaylistEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PlaylistEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PlaylistEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PlaylistEdit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                DBManager.openConnection();//Ksekina ton entity manager
                new PlaylistEdit(null).setVisible(true);
               
            }
        });
    }
    /*
    * A.T. Dimiourgia Model gia ton pinaka me olla ta tragoudia
    */
    private void setAllList(){
        //A.T. Pairnoume to model toy jTable poy tha doylepsoume
        modelALL = (DefaultTableModel) jTableAll.getModel();
        
        //A.T. Adiazoume to Model ,arxikopoiisi
        modelALL.setRowCount(0);
        
        //A.T. _Search_ pernoume to(a) search term(s) kai ta bazoume se array
        // episis thetoume boolean an theloume search
        boolean doSearch = false;
        String[] searchTerms = {};
        if (jTextFieldSearch.getText().equals("*")){
            doSearch = false;
        }else{
            doSearch = true;
            searchTerms =jTextFieldSearch.getText().split("\\s+");
        }

        //A.T. Pairnoume olla ta tragoudia me query apo to PoJo
        //  Song kai gia kathe result so pernoyme to AlbumIDd
        em.getTransaction().begin();          
        em.flush();
        em.clear();
        em.getTransaction().commit();
        Query query = this.em.createQuery("SELECT c FROM Song c");
        List<Song> soL =(List<Song>)query.getResultList();

        for ( Song so : soL) {
            Album al = so.getAlbumId();
            //A.T. prota me solo artists
            // Gia kathe AlbumId diapername tin ArtistList tou
            // kai dimioyrgoyme to rowToAdd pou bazoume sto 
            // Model tou jTable
            //List<model.AlbumArtist> aa = al.getAlbumArtistList(); 
            for (model.AlbumArtist  aa : al.getAlbumArtistList()){
                Artist a =aa.getArtistId();
                System.out.println(a.getArtisticname());
                Object[] rowToAdd = {so.getTitle(),
                        a.getArtisticname(),so.getDuration()};
                if (doSearch){//A.T. an theloume search
                    for (String term: searchTerms){
                        if (so.getTitle().contains(term) || 
                                           a.getArtisticname().contains(term)){
                            modelALL.addRow(rowToAdd); //A.T. to serach term 
                                      //periexete ara to prosthetoume sto model 
                        }
                        
                    }
                }else{//A.T. Oxi search opote to prosthetoume sto model
                    modelALL.addRow(rowToAdd);
                }
            }
            //A.T. stin sinexia ta tragoudia ton  musicgroup
            // Omoia me ArtistList alla tora gia ta Musicgroup
            // Des db diagram (Kathe Album sindeete me sxesi 
            // ManytoMany me artist kai musigroup kai epidi theloume 
            // olla ta tragoudia diapername kai to ArtistList kai 
            // to MusicgroupList
            for (model.AlbumMg mm : al.getAlbumMgList()){
                model.Musicgroup m = mm.getMusicgroupId();
                System.out.println(m.getName());
                Object[] rowToAdd = {so.getTitle(),
                        m.getName(),so.getDuration()};
                if (doSearch){//A.T. an theloume search
                    for (String term: searchTerms){
                        if (so.getTitle().contains(term) || 
                                                 m.getName().contains(term)){
                            modelALL.addRow(rowToAdd);//A.T. to serach term 
                                      //periexete ara to prosthetoume sto model
                        }
                        
                    }
                }else{//A.T. Oxi search opote to prosthetoume sto model
                    modelALL.addRow(rowToAdd);
                }
            }
            
        }
    }
    /*
    * A.T. dimiourgia Model gia ton pinaka me ta tragoudia tis playlist
    * TODO:edit form
    */
    private void setPLList(){
    
        modelPL = (DefaultTableModel) jTablePL.getModel();
    
        Query query = this.em.createQuery("SELECT c "
                + "FROM Song AS c JOIN c.playlistList cc "
                + "WHERE cc.playlistId = :plID");
        query.setParameter("plID", pLIdIn);
        for ( Song so : (List<Song>)query.getResultList()) {
            Album al = so.getAlbumId();
            //A.T. prota me solo artists           
            for (model.AlbumArtist  aa : al.getAlbumArtistList()){
                Artist a =aa.getArtistId();
                System.out.println(a.getArtisticname());
                Object[] rowToAdd = {so.getTitle(),
                            a.getArtisticname(),so.getDuration()};
                modelPL.addRow(rowToAdd);
            }
            //A.T. stin sinexia ta tragoudia ton  musicgroup
            for (model.AlbumMg mm : al.getAlbumMgList()){
                model.Musicgroup m = mm.getMusicgroupId();
                System.out.println(m.getName());
                Object[] rowToAdd = {so.getTitle(),
                            m.getName(),so.getDuration()};
                modelPL.addRow(rowToAdd);
            }
            
        }
        
    }
    
    /*
    Custom filter for file1 FileChooser
    */
        class MyCustomFilter extends javax.swing.filechooser.FileFilter {
        @Override
        public boolean accept(File file) {
            // Allow only directories, or files with ".txt" extension
            return file.isDirectory() || file.getAbsolutePath
                                                    ().endsWith(".xml");
        }
        @Override
        public String getDescription() {
            // This description will be displayed in the dialog,
            // hard-coded = ugly, should be done via I18N
            return "XML documents (*.xml)";
        }
    } 
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser file1;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonIn;
    private javax.swing.JButton jButtonOut;
    private javax.swing.JButton jButtonRXML;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JButton jButtonWXML;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTableAll;
    private javax.swing.JTable jTablePL;
    private javax.swing.JTextField jTextFieldCreat;
    private javax.swing.JTextField jTextFieldDescr;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTextFieldSearch;
    // End of variables declaration//GEN-END:variables
}
